import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";

const initialState = {
  user: "张三",
  age: 18,
  sex: "男",
  list: [],
};

export const login = createAsyncThunk("user/login", async () => {
  // 模拟异步情况
  await new Promise((resolve) => setTimeout(resolve, 2000));
  const resp = { code: 200, data: ["a", "b", "c", "d"] };
  return resp.data;
});

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    addAge(state, action: PayloadAction<number>) {
      state.age += action.payload;
    },
  },
  extraReducers: {
    [login.pending.type]() {
      console.log("数据开始请求");
    },
    [login.fulfilled.type](state, action) {
      console.log("数据请求成功");
      state.list = action.payload;
    },
    [login.rejected.type](state, action) {
      console.log("数据请求失败");
    },
  },
});

export default userSlice;
export const { addAge } = userSlice.actions;
